<template>
  <div>
    <input type="file" class="file" ref="file" @change="uploadAvatar" />
    <img :src="pic" alt class="avatar" @click="handleClick" />
  </div>
</template>

<script>
import { uploadpic } from "@/api";
import { axios, baseURL } from "@/utils/axios";
export default {
  props: ["userinfo"],
  data() {
    return {
      pic: require("@/assets/images/3.jpg"),
    };
  },
  mounted() {
    // 判断是否上传过头像
    if (this.userinfo) {
      if (this.userinfo.avatar) {
        this.pic = this.userinfo.avatar.replace(/public/, baseURL);
      } else {
        this.pic = require("@/assets/images/3.jpg");
      }
    } else {
      this.pic = require("@/assets/images/3.jpg");
    }
  },
  methods: {
    handleClick() {
      this.$refs.file.click();
    },
    uploadAvatar() {
      var file = this.$refs.file.files[0];
      // 创建表单对象
      var data = new FormData();
      data.append("avatar", file);
      uploadpic(data).then((res) => {
        if (res.type) {
          this.pic = res.avatar.replace(/public/, baseURL); // 图片地址优化
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.avatar {
  width: 45px;
  height: 45px;
  border-radius: 50%;
  cursor: pointer;
}
.file {
  display: none;
}
</style>